﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnlockingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnlockingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnlockingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            string orderNo,infoSeq,periodId;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var order = ctx.ApptOrders.Where(x => x.Id == orderId).
                    Select(x => new
                    {
                        x.OrderNo,
                        x.InfoSeq,
                        x.Sqno
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
                orderNo = order.OrderNo;
                infoSeq = order.InfoSeq;
                periodId = order.Sqno;
            }

            //执行取消锁号操作
            var unlockRequest = new ExeUnLockSourceRequest();
            unlockRequest.LockId = orderNo;
            unlockRequest.InfoSeq = infoSeq;
            unlockRequest.PeriodId = periodId;

          
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisSp/ExeUnLockSource", unlockRequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                ExeUnLockSourceResponse unlockResponse = responseMsg.Content.ReadAsAsync<ExeUnLockSourceResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内取消锁号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
            }


            return new ConsumedResult
            {
                Ack = true
            };
        }
    }
}